<template>
  <!-- 修改成长值 -->
  <el-dialog
    v-model="visible"
    :title="$t('user.updateGrowth')"
    width="30%"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      :label-width="$t('language') === 'language' ? '160px' : '100px'"
      @submit.prevent
    >
      <el-form-item
        :label="$t('user.growthTip2')"
        prop="growthValue"
      >
        <el-input-number
          v-model="dataForm.growthValue"
          :max="100000000"
          :min="-100000000"
          class="growthValue"
          :controls="false"
          step-strictly
          @change="inputNumber"
        />
        <span>{{ $t('user.growthTip1') }}</span>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('user.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="confirm"
        >
          {{ $t('user.confirm') }}
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { Debounce } from '@/utils/debounce'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataForm = reactive({
  growthValue: null,
  userIds: []
})

const validateNumber = (rule, value, callback) => {
  if (!/^(-)?[1-9]+[0-9]*$/.test(value)) {
    callback(new Error($t('user.growthTip3')))
  } else {
    callback()
  }
}
const dataRule = {
  growthValue: [
    { required: true, message: $t('user.growthTip4'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
}

const visible = ref(false)
const init = (ids) => {
  visible.value = true
  dataForm.userIds = ids
  dataForm.growthValue = null
}

const inputNumber = () => {
  if (dataForm.growthValue >= 100000000) {
    dataForm.growthValue = 100000000
  } else if (dataForm.growthValue <= -100000000) {
    dataForm.growthValue = -100000000
  }
}

const dataFormRef = ref(null)
const confirm = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    if (!dataForm.userIds) {
      return
    }
    http({
      url: http.adornUrl('/user/userLevel/updateBatchGrowth'),
      method: 'put',
      data: http.adornData(dataForm)
    }).then(() => {
      ElMessage({
        message: $t('user.succeeded'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
          dataForm.growthValue = null
        }
      })
    }).catch(() => {})
  })
}, 1000)

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
:deep(.growthValue){
  width: 100%;
  display: block;
  input{
    text-align: left;
  }
}
</style>
